#! /usr/bin/env python
# -*- coding: utf-8 -*-
#MIT License
#By : cocobear.cn@Gmail.com
#Ver:0.2

from copy import copy
import time
import exceptions
from time import sleep

from PyFetion import *


FetionLoginInterval=600

def GetTimeString():
	return time.strftime("%y/%m/%d %H:%M:%S", time.localtime())
def FetionLogin(phone):
	global FetionLoginInterval
	print GetTimeString()
	print "logging in"
	while(1):
		ret=False
		try:
			if phone.receving:
				phone.logout()
			ret = phone.login(FetionOnline)
		except PyFetionSupportError,e:
			print("Fetion not registered for this phone number")
		except PyFetionAuthError,e:
			print("Phone/Password error")
		except PyFetionSocketError,e:
			print(e.msg)
			print("network error")
		if ret:
			phone.receving=True
			print("Login Success")
			return True
		else:
			print("Login failed retrying in %d seconds"%FetionLoginInterval)
			time.sleep(FetionLoginInterval)

#==========================
# Fetion
class FetionClient:
	def __init__(self, mobile_num, password):
		self.phone = PyFetion(mobile_num,password,"HTTP",debug=False)
		FetionLogin(self.phone)
	def sendMessage(self, receiver, message):
		print('trying to send message to %s:(%s)'%(receiver,message))
		if receiver==None or receiver=='self' or receiver=='me':
			if self.phone.send_sms(toUTF8(message)):
				print("message sent")
			else:
				print("error sending message")
			return
		if not receiver.isdigit() or receiver.isdigit() and len(receiver)!=11: 
			# sending to a name
			contactlist = copy(self.phone.contactlist)

			for i in contactlist:
				if contactlist[i][0] == '':
					contactlist[i][0] = i[4:4+9]
			for c in contactlist.items():
				if c[1][0] == receiver:
					to = c[0]
					if self.phone.send_sms(toUTF8(message),to):
						print("message sent")
					else:
						print("error sending message")
					return 
			print("cannot find name %s" % receiver)
			return
		#send to a number
		contactlist = copy(self.phone.contactlist)
		to=''
		for c in contactlist.items():
			if c[1][1] == receiver:
				to = c[0]
		if not to:
			print("the number is not friend")
			return
		if self.phone.send_sms(toUTF8(message),to):
			print("message sent")
		else:
			print("error sending message")


#==========================
# other
def toUTF8(str):
	#return str.decode((os.name == 'posix' and 'utf-8' or 'cp936')).encode('utf-8')
	return str


